package com.daocao.hua.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.daocao.hua.R;
import com.daocao.hua.api.callback.MyPsersonalContract;
import com.daocao.hua.api.requestInfo.MyPersonalRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.event.ChangePhoneSuccess;
import com.daocao.hua.event.OnCloseMyfund;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.impl.RepayInfoImpl;
import com.daocao.hua.model.LoginAndRegisterModel;
import com.daocao.hua.model.RepayModel;
import com.daocao.hua.model.UploadImageModel;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.uploadImage.UploadImgAdapter;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xsooy-pc on 2017/5/22.
 */

public class MyPersonalActivity extends BaseActivity implements MyPsersonalContract.View {
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.layout_phone)
    RelativeLayout layoutPhone;
    @BindView(R.id.txt_nickname)
    TextView txtNickname;
    @BindView(R.id.layout_nickname)
    RelativeLayout layoutNickname;
    @BindView(R.id.txt_password)
    TextView txtPassword;
    @BindView(R.id.layout_password)
    RelativeLayout layoutPassword;
    @BindView(R.id.txt_email)
    TextView txtEmail;
    @BindView(R.id.layout_email)
    RelativeLayout layoutEmail;
    @BindView(R.id.btn)
    TextView btn;
    @BindView(R.id.img_first_icon)
    CircleImageView imgFirst;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.layout_icon)
    RelativeLayout layoutIcon;
    @BindView(R.id.img_icon_back)
    ImageView imageView;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.txt_phone_left)
    TextView txtPhoneLeft;
    @BindView(R.id.img_phone_icon)
    ImageView imgPhoneIcon;
    @BindView(R.id.txt_nickname_left)
    TextView txtNicknameLeft;
    @BindView(R.id.img_nickname_icon)
    ImageView imgNicknameIcon;
    @BindView(R.id.txt_password_left)
    TextView txtPasswordLeft;
    @BindView(R.id.img_password_icon)
    ImageView imgPasswordIcon;
    @BindView(R.id.txt_email_left)
    TextView txtEmailLeft;
    @BindView(R.id.img_email_icon)
    ImageView imgEmailIcon;
    @BindView(R.id.txt_address_left)
    TextView txtAddressLeft;
    @BindView(R.id.img_address_icon)
    ImageView imgAddressIcon;
    @BindView(R.id.layout_address)
    RelativeLayout layoutAddress;
//    @BindView(R.id.view)
//    View view;
    @BindView(R.id.txt_guesture_left)
    TextView txtGuestureLeft;
    @BindView(R.id.switch_btn)
    SwitchButton switchBtn;
    @BindView(R.id.layout_guesture)
    RelativeLayout layoutGuesture;
    @BindView(R.id.txt_guesture_setting_left)
    TextView txtGuestureSettingLeft;
    @BindView(R.id.img_guesture_setting)
    ImageView imgGuestureSetting;
    @BindView(R.id.layout_guesture_setting)
    RelativeLayout layoutGuestureSetting;
    private Unbinder unbinder;
    private MyPersonalRequest api;
    private UploadImgAdapter uploadImgAdapter;

    //    个人中心
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_my_personal);
        baseInitView(this, "MyPersonalActivity", Const.ViewType.ACTIVITY);
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        EventBus.getDefault().register(this);
        setBackIntent();
        setTitleText("个人中心");
        api = MyPersonalRequest.create();
        api.attachView(this);

        switchBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                //TODO do your job
                if (UI.toString(txtGuestureSettingLeft).equals("设置手势密码")) {
                    ToastUtil.makeText(MyPersonalActivity.this, "您尚未绘制手势密码");
                } else {
                    UserGlobal.setIsOpenGuesture(isChecked);
                }

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        api.detachView();
        unbinder.unbind();
        unbinder = null;
    }


    @Override
    protected void onResume() {
        super.onResume();
        initbutton();
    }


    /**
     * 是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (!PreferenceUtils.getBoolean(this, "is_logined", false)) {
            ToastUtil.makeText(this, getResources().getString(R.string.please_login), Toast.LENGTH_SHORT);
            Util.startActivity(this, V3LoginByCodeActivity.class);
            return false;
        }
        return true;
    }


    /**
     * 初始化按钮
     */
    private void initbutton() {
        if (!PreferenceUtils.getBoolean(this, "is_logined", false)) {
            txtNickname.setVisibility(View.VISIBLE);
            btn.setText(getResources().getString(R.string.login));
            txtNickname.setText(getResources().getString(R.string.please_login));
            txtNickname.setText("");
            txtEmail.setText("");
            txtPhone.setText("");
//            imgIcon.setVisibility(View.GONE);

            imgIcon.setImageResource(R.mipmap.img_my_default_sex);
        } else {
            txtNickname.setVisibility(View.VISIBLE);
            btn.setText(getResources().getString(R.string.logout));
            if (!UserGlobal.hasUsername()) {
                txtNickname.setText("未设置");
                txtNickname.setTextColor(0xFFE3473D);
            } else {
                txtNickname.setTextColor(0xFF6C6C6C);
                txtNickname.setText(UserGlobal.getUsername());
            }
            txtPhone.setText(PreferenceUtils.getString(this, "mobile", ""));
            if (TextUtils.isEmpty(PreferenceUtils.getString(this, "email", ""))) {
                txtEmail.setText("未认证");
                txtEmail.setTextColor(0xFFE3473D);
            } else {
                txtEmail.setText(PreferenceUtils.getString(this, "email", ""));
                txtEmail.setTextColor(0xFF6C6C6C);
            }

            if (PreferenceUtils.getInt(this, "sex", 0) == 0) {
                Glide.with(this).load(PreferenceUtils.getString(this, "header", "")).dontAnimate().placeholder(R.mipmap.img_my_girl).error(R.mipmap.img_my_girl).into(imgFirst);
            } else {
                Glide.with(this).load(PreferenceUtils.getString(this, "header", "")).dontAnimate().placeholder(R.mipmap.img_my_boy).error(R.mipmap.img_my_boy).into(imgFirst);
            }
            txtAddress.setText(PreferenceUtils.getString(this, "address_city", ""));
        }
        if (isSetGuesture()) {
            switchBtn.setEnabled(true);
            txtGuestureSettingLeft.setText("修改手势密码");
        } else {
            switchBtn.setEnabled(false);
            txtGuestureSettingLeft.setText("设置手势密码");
        }
        if(UserGlobal.getIsOpenGuesture()){
            switchBtn.setChecked(true);
        }else {
            switchBtn.setChecked(false);
        }
    }


    @OnClick({R.id.layout_phone, R.id.layout_nickname, R.id.layout_password, R.id.layout_email, R.id.layout_icon, R.id.btn, R.id.layout_address})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.layout_address:
                if (isLogin()) Util.startActivity(this, AddressActivity.class);
                break;
            case R.id.layout_phone:
                if (isLogin()) getRepayInfo();
                break;
            case R.id.layout_nickname:
                if (isLogin()) Util.startActivity(this, NicknameActivity.class);
                break;
            case R.id.layout_password:
                if (isLogin()) {
                    if (UserGlobal.isSetPass()) {
                        Util.startActivity(this, UpdatePwdActivity.class);
                    } else {
                        Util.startActivity(this, V3SetNewPassActivity.class);
                    }
                }
                break;
            case R.id.layout_email:
                if (!isLogin()) {
                    return;
                }
                String isPass = PreferenceUtils.getString(this, "emailpassed", "");
                if (!TextUtils.isEmpty(isPass)) {
                    if (isPass.equals("1")) {
                        Intent intent = new Intent(this, V3EmailIdentityActivity.class);
                        intent.putExtra("isIdentity", isPass);
                        intent.putExtra("email", PreferenceUtils.getString(this, "email", ""));
                        startActivity(intent);
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    } else {
                        Intent intent = new Intent(this, V3EmailIdentityActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    }
                } else {
                    Intent intent = new Intent(this, V3EmailIdentityActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                }
                break;
            case R.id.btn:
                if (isLogin()) {
                    logout();

                } else {
                    Util.startActivity(this, V3LoginByCodeActivity.class);
                    finish();
                }
                break;
            case R.id.layout_icon:
                if (isLogin()) {
                    if (uploadImgAdapter == null) {
                        initUploadImgAdapter();
                    }
                    uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
                }
                break;
        }
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    imgIcon.setVisibility(View.VISIBLE);
                    imgFirst.setVisibility(View.GONE);
                    imgIcon.setImageBitmap(file);
//                    Glide.with(MyPersonalActivity.this).load(file)
//                            .diskCacheStrategy(DiskCacheStrategy.NONE)
//                            .skipMemoryCache(true).
//                            into(imgIcon);
//                    Glide.with(MyPersonalActivity.this).load(file).asBitmap()
//                            .diskCacheStrategy(DiskCacheStrategy.NONE)
//                            .skipMemoryCache(true).
//                            into(new ImageViewTarget<Bitmap>(imgIcon) {
//                                @Override
//                                protected void setResource(Bitmap resource) {
//                                    imgIcon.setImageBitmap(resource);
//
//                                }
//                            });
                    api.updateHead(ImageUtil.Bitmap2StrByBase64(file));
                }
            }
        });
    }

    /**
     * 退出登录广播
     */
//    private void sendBroadcast() {
//        Map<String, String> map = new HashMap<>();
//        map.put("type", Const.SendType.LOGOUT);
//        EventBus.getDefault().post(new OnHomeEventMsg(map));
//    }

    /**
     * 退出登录
     */
    private void logout() {
        PreferenceUtils.putBoolean(getApplicationContext(), "is_logined", false);
        api.logout();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ChangePhoneSuccess msg) {
        txtPhone.setText(Util.replaceString(PreferenceUtils.getString(this, "mobile", ""), 5, 4, '*'));
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    public void onRequestStart() {

    }

    @Override
    public void logoutSuccess(LoginAndRegisterModel item) {
        ToastUtil.makeText(getApplicationContext(), item.getMsg(), Toast.LENGTH_SHORT).show();
//        Util.clearUserInfo(getApplicationContext());
        UserGlobal.logout();
        initbutton();
//        sendBroadcast();
        finish();
    }

    @Override
    public void updateHeadSuccess(UploadImageModel item) {
        api.uploadAddress(item.getUrl());
    }

    @Override
    public void uploadAddressSuccess() {
        ToastUtil.makeText(this, "上传成功").show();
        Map<String, String> map = new HashMap<>();
        map.put("type", Const.SendType.UPDATE);
        EventBus.getDefault().post(new OnHomeEventMsg(map));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }


    /**
     * 获取还款信息
     */
    private void getRepayInfo() {
        new RepayInfoImpl().getRepayInfo(this, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                RepayModel model = (RepayModel) o;
                if (TextUtils.isEmpty(model.getData().getId())) {
//                    0未实名，1已实名
                    if (PreferenceUtils.getString(MyPersonalActivity.this, "idcardpassed", "0").equals("0")) {
                        Dialog.gotoShiMing(MyPersonalActivity.this, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                Util.startActivity(MyPersonalActivity.this, AutonymActivity.class);
                            }

                            @Override
                            public void cancel() {

                            }
                        }).show();
                    } else {
                        Util.startActivity(MyPersonalActivity.this, ChangePhoneTotalActivity.class);
                    }
                    return;
                }
//                有借款
                Dialog.gotoRepayMoney(MyPersonalActivity.this, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        EventBus.getDefault().post(new OnCloseMyfund());
                        sendEventBus();
                        finish();
                    }

                    @Override
                    public void cancel() {

                    }
                }).show();
            }

            @Override
            public void onFailure(String cause) {
                ToastUtil.makeText(MyPersonalActivity.this, cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sendEventBus() {

        Map<String, String> map = new HashMap<>();
        map.put("type", Const.SendType.SWITCH_PAGE);
        map.put("currentIndex", Const.View.REPAY_VIEW + "");
        EventBus.getDefault().post(new OnHomeEventMsg(map));
        Util.startActivity(this, MainActivityNew.class);
        finish();
    }

    @OnClick({R.id.layout_guesture_setting})
    public void onViewClicked1(View view) {
        switch (view.getId()) {

            case R.id.layout_guesture_setting:
                if (UI.toString(txtGuestureSettingLeft).equals("设置手势密码")) {
                    Intent intent = new Intent(this, CreateGestureActivity.class);
                    intent.putExtra("is_check", true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                } else {
                    Intent intent=new Intent(this,GestureLoginActivity.class);
                    intent.putExtra("is_check",true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//                    Util.startActivity(this, GestureLoginActivity.class);
                }
                break;
        }
    }
}
